import React from 'react'
import { RouterRawState } from '../../types';
import { Navigate } from 'react-router-dom';

interface PropsType {
  v: RouterRawState
}

const BeforeEachRouter: React.FC<PropsType> = ({ v }) => {
  // const navigate = useNavigate()
  /* 定义白名单 */ 
  const whiteList = ['/login', '/regist'];
  /* 获取 token */
  const token = localStorage.getItem('token');
  /* 拦截 */ 
  // 1. 是否进入白名单页面
  if(whiteList.includes(v.path)) {
    // 1-1 是
    // 1-1-1 是否存在token
    if(token) {
      // 是 拦截进入首页
      return <Navigate to="/"></Navigate>
    } else {
      return v.element
    }
  } else {
    // 1-2 否
    if(token) {
      // 存在  
      // 判断是否需要权限
      if(!v.roles) return v.element;
      const role = localStorage.getItem('role') as string;

      if(v.roles.includes(role)) {
        return v.element
      } else {
        return  <Navigate to="/403"></Navigate>
      }
    } else {
      // 不存在
      return <Navigate to="/login"></Navigate>
    }
  }
  return v.element
}


export default BeforeEachRouter;